import time
from openpyxl import workbook
from selenium import webdriver
from selenium.webdriver.common.by import By


class AutoClub(object):
    def __init__(self):
        self.driver = webdriver.Chrome()
        # 创建一个数据表
        self.wb = workbook.Workbook()
        # 数据表的一个激活
        self.ws = self.wb.active
        # 添加一下数据表的表头
        self.ws.append(['token_id', '观看数', '点赞数', 'perunit_price', 'dollar_price', 'Last 7 days', 'Last 14 days', 'Last 30 days', 'Last 60 days', 'Last 90 days', 'Last year', 'All time'])

    def start(self):
        for page in range(5484, 10000):
            data_list = []
            # 确定页面的url
            url = f'https://opensea.io/assets/ethereum/0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d/{page}'
            # 开始访问
            self.driver.get(url)
            # 定义当前猴子的代号
            title = '#' + f'{page}'
            # 观看次数
            views = self.driver.find_element(By.XPATH, '//div[@class="sc-1xf18x6-0 sc-13kp31z-0 clHxmt"]').text
            # 喜欢次数
            favorites = self.driver.find_element(By.XPATH, '//button[@class="sc-ty1bh0-0 infdiL sc-1xf18x6-0 sc-13kp31z-0 clHxmt kaWAoE"]').text
            # 这里加判断
            price_name = self.driver.find_elements(By.XPATH, '//img[@alt="ETH"]|//img[@alt="WETH"]|//img[@alt="USDC"]')
            if len(price_name) == 1:
                if price_name[0].get_attribute('alt') == 'ETH':
                    # eth价格
                    perunit_price = self.driver.find_element(By.XPATH, '//div[@class="sc-7qr9y8-0 iUvoJs Price--amount"]').text
                else:
                    perunit_price = None
            else:
                perunit_price = None
            # 添加数据
            data_list.extend([title, views[11:-6], favorites[9:-10], perunit_price])
            # $价格
            dollar_price = self.driver.find_elements(By.XPATH, '//div[@class="sc-7qr9y8-0 iUvoJs Price--fiat-amount Price--fiat-amount-secondary"]')
            # 判断有没有价格
            if len(dollar_price) != 0:
                dollar_price = dollar_price[0].text
                data_list.append(dollar_price[1:-1])
                print('================================')
                print(title)
                print(views[11:-6])
                print(favorites[9:-10])
                print(perunit_price)
                print(dollar_price[1:-1])
            else:
                dollar_price = None
                data_list.append(dollar_price)
                print('================================')
                print(title)
                print(views[11:-6])
                print(favorites[9:-10])
                print(perunit_price)
                print(dollar_price)
            # 爬取不同时间段的avg.time
            for date in range(1, 8):
                data_list.extend(self.process(date))
            self.ws.append(data_list)
            self.wb.save(f'monkey_2数据.xlsx')
            print('该数据已加载')
            print(data_list)
            print('================================')
        # 打印提示信息
        print('所有事件处理完成')
        # 关闭自动化
        self.driver.close()

    def process(self, date):
        # 对折线图未能正常加载做异常处理
        little_data_list = []
        # 点击选项框
        self.driver.find_element(By.XPATH, '//*[@id="Body assets-item-timeline"]/div/div/div/div[1]/div[1]/div/div/div/i').click()
        time.sleep(0.5)
        # 点击选项
        self.driver.find_element(By.XPATH, f'//*[@id="Body assets-item-timeline"]/div/div/div/div[1]/div/div/div[2]//ul/li[{date}]').click()
        time.sleep(1)
        line_diagram = self.driver.find_elements(By.XPATH, '//div[@class="sc-dy59cl-0 eXnWvj Image--isImageLoaded Image--isImageLoaderVisible PriceHistory--no-data-img" or @class="recharts-responsive-container PriceHistory--chart"]')
        # 超时处理
        if len(line_diagram) == 0:
            times_1 = 2
            times_2 = 3
            self.loop(date, times_1, times_2)
            # 获取数据折线图的的提示信息
        hint_text = self.driver.find_elements(By.XPATH, '//div[@class="PriceHistory--no-data-text"]')
        # 如果没有数据，结果为空，如有有数据，就展示所搜集的结果
        if len(hint_text) == 1:
            print('没有记录')
            little_data_list.append(None)
        else:
            print('有记录')
            avg_price = self.driver.find_element(By.XPATH, '//p[@class="sc-1xf18x6-0 sc-1w94ul3-0 iUhqVy doEVTy"]').text[1:]
            print(f'记录的平均值值为{avg_price}')
            little_data_list.append(f'{avg_price}')
        return little_data_list

    def loop(self, date, times_1, times_2):
        print('折线图未正常加载超时处理')
        # 点击选项框
        self.driver.find_element(By.XPATH, '//*[@id="Body assets-item-timeline"]/div/div/div/div[1]/div[1]/div/div/div/i').click()
        time.sleep(times_1)
        # 点击选项
        self.driver.find_element(By.XPATH, f'//*[@id="Body assets-item-timeline"]/div/div/div/div[1]/div/div/div[2]//ul/li[{date}]').click()
        time.sleep(times_2)
        line_diagram = self.driver.find_elements(By.XPATH, '//div[@class="sc-dy59cl-0 eXnWvj Image--isImageLoaded Image--isImageLoaderVisible PriceHistory--no-data-img" or @class="recharts-responsive-container PriceHistory--chart"]')
        if len(line_diagram) == 0:
            print('时间延长')
            times_1 += 0.5
            times_1 += 0.5
            self.loop(date, times_1, times_2)


if __name__ == '__main__':
    a = AutoClub()
    a.start()
